import React, { useEffect, useState } from "react"
import { getData } from "../api/getInitData";
import { useOnEventBus } from "../eventBus/eventBus";

const MainContext = React.createContext({
    name: "xulc",
    age: 32
});

function MainContextProvider({
    children,
    ...props
}){

    const [,updater] = useState({});

    const [data, setData] = useState({
        loading: true
    });

    useEffect(()=>{

        getData().then(function(resultData){
            setData({
                ...{
                    loading: false
                },
                ...{
                    mainChange : function(){
                        // updater({});
                    }
                },
                ...resultData
            })
        })

    }, [])

    if(data.loading){
        return <p>加载中....</p>
    }

    return <MainContext.Provider value={{...data, ...props}}>
        {children}
    </MainContext.Provider>
}

function useMainContext(){
    const context = React.useContext(MainContext);
    const [,updater] = useState({});
    useOnEventBus("main.update", function(){
        // updater({});
        //console.log('mainContext', context);
    })
    if(context === undefined){
        throw console.error("useMainContext必须包含在MainContextProvider上下文内");
        return {};
    }else{
        return context;
    }
}

export {
    MainContextProvider,
    useMainContext,//main上下文
}